package com.ccsu.joysport.service;

import com.ccsu.joysport.controller.model.resp.AdminClubResp;
import com.ccsu.joysport.dto.*;
import com.ccsu.joysport.entity.*;
import com.ccsu.joysport.repository.*;
import com.ccsu.joysport.util.JwtUtil;
import io.jsonwebtoken.JwtException;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class AdminClubService {

    @Autowired
    private ClubRepository clubRepository;

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private ManagerRepository managerRepository;

    @Autowired
    private ClubApplicationRepository clubApplicationRepository;
    @Autowired
    private  StudentClubRepository studentClubRepository;

    public ClubResponse addClubInfo(AddClubInfoRequest request) {
        // 解析token获取管理员ID
        String OperatorId;
        try {
            OperatorId = jwtUtil.extractId(request.getAdminToken());
        } catch (JwtException e) {
            return new ClubResponse("failed", "token解析失败");
        }
        student student = studentRepository.findByStudentNumber(OperatorId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "未找到学生信息"));
        String ClubUserName = student.getName();
        Club club = new Club();
        club.setClubId(request.getClubId());
        club.setClubName(request.getClubName());
        club.setClubDesc(request.getClubDesc());
        club.setClubLogo(request.getClubLogo());
        club.setCollege(request.getCollege());
        club.setClubUser(OperatorId);
        club.setClubUserName(ClubUserName);
        //管理员创建的俱乐部默认通过申请
        club.setStatus("approve");
        club.setClubCreate(new Timestamp(System.currentTimeMillis()));
        club.setEntryRestrictions(request.getEntryRestrictions());
        clubRepository.save(club);
        return new ClubResponse("success", "俱乐部信息添加成功");
    }

    public ClubResponse deleteClubInfo(DeleteClubInfoRequest request) {
        Club club = clubRepository.findById(request.getClubId())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "未找到俱乐部"));
        clubRepository.delete(club);
        return new ClubResponse("success", "俱乐部信息删除成功");
    }

    public ClubResponse editClubInfo(EditClubInfoRequest request) {
        Club club = clubRepository.findById(request.getClubId())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "未找到俱乐部"));

        if (request.getClubName() != null) club.setClubName(request.getClubName());
        if (request.getClubDesc() != null) club.setClubDesc(request.getClubDesc());
        if (request.getClubLogo() != null) club.setClubLogo(request.getClubLogo());
        if (request.getCollege() != null) club.setCollege(request.getCollege());
        if (request.getEntryRestrictions() != null) club.setEntryRestrictions(request.getEntryRestrictions());

        clubRepository.save(club);
        return new ClubResponse("success", "俱乐部信息修改成功");
    }

    public Club viewClubInfo(String clubId) {

        Club club = clubRepository.findById(clubId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "未找到俱乐部"));

        // 实时更新 memberCount
        int memberCount = studentClubRepository.countMembersByClubId(clubId);
        club.setMemberCount(memberCount);

        return club;
    }

    @Autowired
    private JwtUtil jwtUtil;


    @Autowired
    private ClubOperatorRepository clubOperatorRepository;

    public ClubResponse inviteOperator(InviteOperatorRequest request) {
        // 解析token获取管理员ID
        String OperatorId;
        try {
            OperatorId = jwtUtil.extractId(request.getAdminToken());
        } catch (JwtException e) {
            return new ClubResponse("failed", "token解析失败");
        }

        // 根据学生学号和姓名判断是否存在该学生
        boolean studentExists = studentRepository.existsByStudentNumberAndName(request.getOperatorStudentId(), request.getOperatorName());
        if (!studentExists) {
            return new ClubResponse("failed", "未找到学生");
        }

        // 检查俱乐部是否存在
        clubRepository.findById(request.getClubId())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "俱乐部未找到"));

        // 检查是否已有相同的操作者记录
        boolean exists = clubOperatorRepository.existsByClubIdAndOperatorNameAndOperatorStudentId(
                request.getClubId(), request.getOperatorName(), request.getOperatorStudentId());

        if (exists) {
            return new ClubResponse("failed", "该操作者已存在");
        }

        // 添加新的操作者记录
        ClubOperator clubOperator = new ClubOperator();
        clubOperator.setClubId(request.getClubId());
        clubOperator.setOperatorName(request.getOperatorName());
        clubOperator.setOperatorStudentId(request.getOperatorStudentId());
        clubOperator.setOperatorId(OperatorId);
        clubOperator.setOperatorTime(Timestamp.from(Instant.now()));
        clubOperatorRepository.save(clubOperator);

        return new ClubResponse("success", "邀请操作者成功");
    }


    public ClubResponse deleteOperator(DeleteOperatorRequest request) {
        ClubOperator clubOperator = clubOperatorRepository.findByClubIdAndOperatorStudentId(request.getClubId(), request.getOperatorStudentId())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "未找到操作者"));

        clubOperatorRepository.delete(clubOperator);

        return new ClubResponse("success", "删除操作者成功");
    }

    public List<AdminClubResp> reviewList() {

        List<Club> all = clubRepository.findAll();

        Map<String, Club> clubIdAndInfoMap = all.stream().collect(Collectors.toMap(Club::getClubId, club -> club));

        List<Club> clubList = clubRepository.findByClubIdIn(new ArrayList<>(clubIdAndInfoMap.keySet()));

        List<String> studentIds = clubList.stream().map(Club::getClubUser).collect(Collectors.toList());

        List<student> studentList = studentRepository.findBystudentNumberIn(studentIds);

        Map<String, student> stuNoAndInfoMap = studentList.stream().collect(Collectors.toMap(student::getStudentNumber, student -> student));

        return clubList.stream().map(club -> {
            AdminClubResp adminClubResp = new AdminClubResp();

            BeanUtils.copyProperties(club, adminClubResp);

            adminClubResp.setProposer(getUserInfo(stuNoAndInfoMap.get(club.getClubUser())));
            adminClubResp.setApplyReason(clubIdAndInfoMap.get(club.getClubId()).getApplyReason());
            adminClubResp.setStatus(clubIdAndInfoMap.get(club.getClubId()).getStatus());

            Date applicationTime = clubIdAndInfoMap.get(club.getClubId()).getGmtCreate();
            adminClubResp.setApplyTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(applicationTime));
            adminClubResp.setReviewRemark(clubIdAndInfoMap.get(club.getClubId()).getReviewRemark());

            return adminClubResp;
        }).collect(Collectors.toList());
    }

    private String getUserInfo(student student) {
        if (student == null) {
            return "未找到对应的学生信息";
        }

        return new StringJoiner(" | ")
                .add(student.getStudentNumber())
                .add(student.getCollege())
                .add(student.getName()).toString();
    }



    public List<ClubResponse> getManagedClubs(String adminId) {
        Manager manager = managerRepository.findByAccount(adminId)
                .orElseThrow(() -> new RuntimeException("未找到管理员信息"));

        String role = manager.getRole();
        if ("super".equals(role)) {
            return clubRepository.findAll().stream()
                    .map(this::toClubResponse)
                    .collect(Collectors.toList());
        } else if ("root".equals(role)) {
            return clubRepository.findByClubUserName(manager.getName()).stream()
                    .map(this::toClubResponse)
                    .collect(Collectors.toList());
        } else if ("operator".equals(role)) {
            throw new RuntimeException("无权限获取俱乐部列表");
        } else {
            throw new RuntimeException("未知的角色权限");
        }
    }

    private ClubResponse toClubResponse(Club club) {
        return new ClubResponse(club.getClubId(), club.getClubName(), club.getClubLogo());
    }


    public List<OperatorResponse> getOperators(String clubId) {
        List<ClubOperator> operators = clubOperatorRepository.findByClubId(clubId);
        return operators.stream()
                .map(op -> new OperatorResponse(op.getOperatorStudentId(), op.getOperatorName(), op.getFormattedInviteTime()))
                .collect(Collectors.toList());
    }

    public List<ApplicationResponse> getApplications(String clubId) {
        List<ClubApplication> applications = clubApplicationRepository.findByClubId(clubId);
        return applications.stream()
                .map(app -> {
                    student student = studentRepository.findByStudentNumber(app.getStudentId())
                            .orElseThrow(() -> new RuntimeException("未找到学生信息"));
                    return new ApplicationResponse(
                            student.getStudentNumber(),
                            student.getName(),
                            student.getMajor(),
                            student.getTeam(),
                            app.getReason(),
                            app.getFormattedApplicationTime(),
                            app.getStatus()
                    );
                })
                .collect(Collectors.toList());
    }
    public List<MemberResponse> getMembers(String clubId) {
        List<StudentClub> studentClubs = studentClubRepository.findByClubId(clubId);
        return studentClubs.stream()
                .map(sc -> {
                    student student = studentRepository.findByStudentNumber(sc.getStudentId())
                            .orElseThrow(() -> new RuntimeException("未找到学生信息"));
                    return new MemberResponse(
                            student.getStudentNumber(),
                            student.getName(),
                            student.getCollege(),
                            student.getMajor(),
                            student.getTeam()
                    );
                })
                .collect(Collectors.toList());
    }

    public DeleteClubResponse deleteMember(DeleteMemberRequest request) {
        StudentClub studentClub = studentClubRepository.findByClubIdAndStudentId(request.getClubId(), request.getStudentId())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "未找到俱乐部成员"));

        studentClubRepository.delete(studentClub);

        return new DeleteClubResponse("success", "删除俱乐部成员成功");
    }


    public HandleCreateClubResponse handleCreateClub(HandleCreateClubRequest request) {
        String flag = request.getAction().equals("approve") ? "通过" : "拒绝";

        // 1. 先查询俱乐部是否存在
        Club club = clubRepository.findByClubId(request.getClubId())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "未找到俱乐部"));

        if ("approve".equals(request.getAction())) {
            // 2. 更新俱乐部审核状态为approve
            club.setStatus("approve");
            clubRepository.save(club);

            // 3. 检查manager表是否存在相同的学生信息（判断：studentId+role是否一致）
            if (!managerRepository.existsByAccountAndRole(club.getClubUser(), "root")) {
                // 4. 添加学生信息至manager
                Manager manager = new Manager();
                manager.setName(club.getClubUserName());
                manager.setAccount(club.getClubUser());
                manager.setPassword("123456");
                manager.setRole("root");
                managerRepository.save(manager);
            }
        } else {
            // 如果拒绝，更新俱乐部状态为reject
            club.setStatus("reject");
            clubRepository.save(club);
        }

        return new HandleCreateClubResponse("success", "俱乐部审核" , flag);
    }

//
//    public HandleJoinClubResponse handleJoinClub(HandleJoinClubRequest request) {
//        HandleJoinClubResponse response = new HandleJoinClubResponse();
//
//        Optional<ClubApplication> optionalApplication = clubApplicationRepository.findByClubIdAndStudentId(request.getClubId(), request.getStudentId());
//        if (optionalApplication.isEmpty()) {
//            response.setStatus("error");
//            response.setMessage("申请不存在");
//            return response;
//        }
//
//        ClubApplication application = optionalApplication.get();
//
//        if (!"wait".equals(application.getStatus())) {
//            response.setStatus("error");
//            response.setMessage("申请已处理");
//            return response;
//        }
//
//        if ("approve".equals(request.getStatus())) {
//            application.setStatus("approve");
//            application.setReason(request.getReason());
//            clubApplicationRepository.save(application);
//
//            StudentClub studentClub = new StudentClub();
//            studentClub.setClubId(request.getClubId());
//            studentClub.setStudentId(request.getStudentId());
//            studentClubRepository.save(studentClub);
//        } else if ("reject".equals(request.getStatus())) {
//            application.setStatus("reject");
//            application.setReason(request.getReason());
//            clubApplicationRepository.save(application);
//        } else {
//            response.setStatus("error");
//            response.setMessage("无效的申请状态");
//            return response;
//        }
//
//        response.setStatus("success");
//        response.setMessage("审核完成");
//        return response;
//    }

    public HandleJoinClubResponse handleJoinClub(HandleJoinClubRequest request) {
        HandleJoinClubResponse response = new HandleJoinClubResponse();

        Optional<ClubApplication> optionalApplication = clubApplicationRepository.findByClubIdAndStudentId(request.getClubId(), request.getStudentId());
        if (optionalApplication.isEmpty()) {
            response.setStatus("error");
            response.setMessage("申请不存在");
            return response;
        }

        ClubApplication application = optionalApplication.get();

        if (!"wait".equals(application.getStatus())) {
            response.setStatus("error");
            response.setMessage("申请已处理");
            return response;
        }

        if ("approve".equals(request.getStatus())) {
            application.setStatus("approve");
            application.setReviewRemark(request.getReviewRemark()); // 设置审核备注
            clubApplicationRepository.save(application);

            StudentClub studentClub = new StudentClub();
            studentClub.setClubId(request.getClubId());
            studentClub.setStudentId(request.getStudentId());
            studentClubRepository.save(studentClub);
        } else if ("reject".equals(request.getStatus())) {
            application.setStatus("reject");
            application.setReviewRemark(request.getReviewRemark()); // 设置审核备注
            clubApplicationRepository.save(application);
        } else {
            response.setStatus("error");
            response.setMessage("无效的申请状态");
            return response;
        }

        response.setStatus("success");
        response.setMessage("审核完成");
        return response;
    }
    public List<AllClubResponse> getAllClubs() {
        return clubRepository.findAll().stream()
                .map(club -> {
                    AllClubResponse clubResponse = new AllClubResponse();
                    clubResponse.setClubId(club.getClubId());
                    clubResponse.setClubName(club.getClubName());
                    return clubResponse;
                })
                .collect(Collectors.toList());
    }
}
